/*
 *      lcm.c
 *      
 *      Copyright 2009 Daniele Ricci <denn86@gmail.com>, Luca Saccagi <luksak86@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

/*		
 *		GCC Compile Options: 
 *		gcc `pkg-config --cflags --libs vortex` `xml2-config --cflags --libs` -lrt lcm.c -o lcm
 */

#include "lcm.h"
#include "lcm_func.c"
#include "configuration.c"
#include "debug.c"



int main(int argc,char **argv){
	int n,i;
	xmlDocPtr doc;	
	struct direct **namelist;  
	VortexChannel *ch;
	VortexConnection *cn;
	VortexAsyncQueue *queue;
	VortexStatus st;
	char *st_m;
	int status;
	char rmcmd[255];
	int results=0;

	version(argc,argv);

	/*ADDED*/ (argc >= 1) ? load_conf(argv[1]) : load_conf(NULL);
	/*DBG*/DEBUG == DBG_CONF ? print_conf(c0) : 0;
	init();
	vortex_init();
	queue=vortex_async_queue_new();
 	vortex_connection_set_auto_tls(true,true,NULL);
	/*MODIF*/cn=vortex_connection_new(c0->srv_ip, c0->srv_port, NULL, NULL);
	/*ADDED*/ch=NULL;
	idmp_connection(cn,ch,queue);
	ch=vortex_channel_new(cn,0,PLAIN_PROFILE,NULL,NULL,NULL,NULL,NULL,NULL);
	vortex_error(cn,ch);			
	vortex_sasl_set_propertie(cn,VORTEX_SASL_AUTH_ID,sasl_get_data("id"),NULL);
	vortex_sasl_set_propertie(cn,VORTEX_SASL_PASSWORD,sasl_get_data("pw"),NULL);
	vortex_sasl_start_auth_sync(cn,VORTEX_SASL_CRAM_MD5,&st,&st_m);
	sasl_verify(cn);
	ch=vortex_channel_new(cn,0,PLAIN_PROFILE,NULL,NULL,vortex_channel_queue_reply,queue,NULL,NULL);
	/*ADDED*/vortex_channel_set_serialize(ch,1);
	vortex_error(cn,ch);
	while(true){
	/******************************************************************/
	/** Scanning High Priority sign directory			 **/
	/******************************************************************/
		n = scandir(c0->dir_hpsign, &namelist, 0, alphasort);
		if(n<0){
			fprintf(stderr,"ERR - Unable to scan %s\n",c0->dir_hpsign);
			vortex_exit();
			exit(-1);
		}
		for(i=0;i<n;i++){
			if(!((namelist[i]->d_name[0]=='.')&&((namelist[i]->d_name[1]=='.')||(namelist[i]->d_name[1]=='\0')))){
				if((doc=sign_dir_polling(c0->dir_hpsign,namelist[i]->d_name))==NULL){
					fprintf(stderr,"ERR - Unable to load signature %s\n",namelist[i]->d_name);
				}else{
					#ifdef _WIN32
					/*MODIF*///rmcmd=(char *)calloc(sizeof(char),strlen(c0->dir_hpsign)+strlen(namelist[i]->d_name)+strlen(RMCMD)+3);
					/*MODIF*/snprintf(rmcmd,strlen(c0->dir_hpsign)+strlen(namelist[i]->d_name)+strlen(RMCMD)+3,"%s\"%s%s\"",RMCMD,c0->dir_hpsign,namelist[i]->d_name);
					#else
					/*MODIF*///rmcmd=(char *)calloc(sizeof(char),strlen(c0->dir_hpsign)+strlen(namelist[i]->d_name)+strlen(RMCMD)+1);
					/*MODIF*/snprintf(rmcmd,strlen(c0->dir_hpsign)+strlen(namelist[i]->d_name)+strlen(RMCMD)+3,"%s\"%s%s\"",RMCMD,c0->dir_hpsign,namelist[i]->d_name);
					#endif
					/*DBG*/DEBUG == DBG_CMD ? printf("MAIN: rmcmd _%s_\n",rmcmd) : 0;
					system(rmcmd);
					//free(rmcmd);	
					/*DBG*/DEBUG == DBG_FILES ? printf("%s\n",namelist[i]->d_name) : 0;
					cur_sign->curstep=-1;
					do{
						status=sign_get_data(doc);				// 0 ok, 1 group not found, -1 error
						if(status>=0){
							if(status==0){
								/*DBG*/DEBUG != DAEMON ? printf("STATUS:%d cur_sign=%s,curstep=%d\n",status,cur_sign->sig_id,cur_sign->curstep) : 0;
								sign_handler(ch,doc);
								/*DBG*/DEBUG == DBG_HASH_VAR ? printf("VAR:\n"), xmlHashScan(var,hash_print,"f") : 0; 
								/*DBG*/DEBUG == DBG_HASH_RES ? printf("RESULT:\n"), xmlHashScan(result,hash_print,"f") : 0;
								/* TIMEOUT HANDLING */
								timeout_start(cur_sign);
								do{
									results=0;
									idmp_query(cn,ch);
									results=results_handler(ch,cn,queue,doc);
								}while(timeout_handler(cur_sign) && results==0);
								/* TIMEOUT HANDLING */
								query2send[strlen(query2send)]='\0';
								query2send=(char *)realloc(query2send,strlen(query2send));
								free(query2send);
							}
							free_structs(doc);
						}else{
							fprintf(stderr,"ERR - Broken signature %s\n",namelist[i]->d_name);
							exit(-1);
						}
					}while(proceed==true);
				}
				/*ADDED*/xmlFreeDoc(doc);
			}
			free(namelist[i]);
		}
		free(namelist);
	/******************************************************************/
	/** Scanning Default sign directory								 **/
	/******************************************************************/
		n = scandir(c0->dir_sign, &namelist, 0, alphasort);
		if(n<0){
			fprintf(stderr,"ERR - Unable to scan %s\n",c0->dir_sign);
			vortex_exit();
			exit(-1);
		}
		for(i=0;i<n;i++){
			if(!((namelist[i]->d_name[0]=='.')&&((namelist[i]->d_name[1]=='.')||(namelist[i]->d_name[1]=='\0')))){
				if((doc=sign_dir_polling(c0->dir_sign,namelist[i]->d_name))==NULL){
					fprintf(stderr,"Unable to load signature %s\n",namelist[i]->d_name);
				}else{
					/*DBG*/DEBUG == DBG_FILES ? printf("%s\n",namelist[i]->d_name) : 0;
					cur_sign->curstep=-1;
					do{
						status=sign_get_data(doc);
						if(status>=0){
							if(status==0){
								/*DBG*/DEBUG != DAEMON ? printf("STATUS:%d cur_sign=%s,curstep=%d\n",status,cur_sign->sig_id,cur_sign->curstep) : 0;
								sign_handler(ch,doc);
								/*DBG*/DEBUG == DBG_HASH_VAR ? printf("VAR:\n"), xmlHashScan(var,hash_print,"f") : 0; 
								/*DBG*/DEBUG == DBG_HASH_RES ? printf("RESULT:\n"), xmlHashScan(result,hash_print,"f") : 0;
								/* TIMEOUT HANDLING */
								timeout_start(cur_sign);
								do{
									results=0;
									idmp_query(cn,ch);
									results=results_handler(ch,cn,queue,doc);
								}while(timeout_handler(cur_sign) && results==0);
								/* TIMEOUT HANDLING */
								query2send[strlen(query2send)]='\0';
								query2send=(char *)realloc(query2send,strlen(query2send));
								free(query2send);
							}
							free_structs(doc);
						}else{
							fprintf(stderr,"ERR - Broken signature %s\n",namelist[i]->d_name);
							exit(-1);
						}
					}while(proceed==true);
				}
				/*ADDED*/xmlFreeDoc(doc);
			}
			free(namelist[i]);
		}
		free(namelist);
		/*MODIF*/usleep(c0->polling_time);
	}
	vortex_connection_close(cn);
	vortex_exit();
	return 0;
}
